// @ts-nocheck
import React, { useState, useEffect, useRef } from "react";
import { observer, useLocalObservable } from "mobx-react-lite";
import RemoteSelect from "@/components/RemoteSelect";
import '@/components/dhtmlx/gantt/codebase/dhtmlxgantt.css?v=7.1.12';
import '@/components/dhtmlx/assets/iconfont/iconfont.css';
import '@/components/dhtmlx/gantt/codebase/dhtmlxgantt.js?v=7.0.7';
import '@/components/dhtmlx/gantt/codebase/locale/locale_cn.js';
import '@/components/dhtmlx/gantt/codebase/ext/dhtmlxgantt_tooltip.js?v=7.0.7';
import '@/components/dhtmlx/assets/iconfont/iconfont.js';
import Store from './store';
import moment from "moment";
import './index.less';
import { getLabel } from "@/common/request/formatter";
import { capacityTypeList } from "@/types/constant/datasource";
import $ from 'jquery';
import { Button, Radio, Spin, Drawer, Form, Select, Checkbox, DatePicker, message } from "antd";
import AsyncSelect from "@/components/AsyncSelect";
import ArrowSvg from '@/assets/svg/youjiantou.svg';
import Style from './index.module.less';
import classNames from 'classnames';
import { getDateTime } from "@/utils";
import { hexToBackRGB } from "@/utils/color";
import language from "@/locales/zh_cn";
import { CloseOutlined } from "@ant-design/icons";

const { RangePicker: DateRangePicker } = DatePicker;
const { Group: RadioGroup } = Radio;
const OrderDispatch = observer((props: any) => {
  const [model, setModel] = useState('hour');
  const [values, setValues] = useState({});
  const [task, setTask] = useState({});
  const [batchList, setBatchList] = useState<any[]>([]);
  const [bomList, setBomList] = useState<any[]>([]);
  const ganttRef = useRef(null);
  const ganttInstance = useRef(null);
  const store = useLocalObservable(() => new Store());
  // const language = useLanguage();

  useEffect(() => {
    if (!ganttRef.current) return;
    
    try {
      // 清理旧的实例
      if (ganttInstance.current) {
        ganttInstance.current.clearAll();
        ganttInstance.current.destructor();
      }

      // 创建新实例
      ganttInstance.current = Gantt.getGanttInstance();
      if (!ganttInstance.current) {
        console.error('Failed to get gantt instance');
        return;
      }

      initGantt();
      setTipEvent();
    } catch (e) {
      console.error('Error initializing gantt:', e);
    }
  }, []);

  useEffect(() => {
    if (!ganttInstance.current) return;
    
    try {
      const currentScrollPosition = ganttInstance.current.getScrollState();
      if (store.elements && store.elements.length > 0) {
        // 直接解析新数据
        ganttInstance.current.parse({
          data: store.elements,
          links: store.links || [],
        });
      }
      
      if (currentScrollPosition) {
        ganttInstance.current.scrollTo(currentScrollPosition.x, currentScrollPosition.y);
      }
    } catch (e) {
      console.error('Error updating gantt data:', e);
    }
  }, [store.elements]);

  const setTipEvent = () => {
    $('#order-dispatch-gantt').off('mouseleave');
    $('#order-dispatch-gantt').on('mouseleave', function() {
      $('.gantt_tooltip').remove();
    });
  }

  const initGantt = () => {
    try {
      let zoomConfig = {
        levels: [
          {
            name: 'hour',
            scale_height: 50,
            min_column_width: 50,
            scales: [
              { unit: 'day', step: 1, format: '%m/%d' },
              { unit: 'hour', step: 1, format: '%H:%i' }
            ]
          },
          {
            name: 'day',
            scale_height: 27,
            min_column_width: 80,
            scales: [
              { unit: 'day', step: 1, format: '%m/%d' }
            ]
          },
          {
            name: 'week',
            scale_height: 50,
            min_column_width: 50,
            scales: [
              {
                unit: 'week', step: 1, format: function (date) {
                  let dateToStr = ganttInstance.current.date.date_to_str('%d %M');
                  let endDate = ganttInstance.current.date.add(date, -6, 'day');
                  let weekNum = ganttInstance.current.date.date_to_str('%W')(date);
                  return '#' + weekNum + ', ' + dateToStr(date) + ' - ' + dateToStr(endDate);
                }
              },
              { unit: 'day', step: 1, format: '%j %D' }
            ]
          },
          {
            name: 'month',
            scale_height: 50,
            min_column_width: 120,
            scales: [
              { unit: 'month', format: '%Y %F' },
              { unit: 'week', format: 'Week #%W' }
            ]
          },
          {
            name: 'quarter',
            scale_height: 50,
            min_column_width: 90,
            scales: [
              { unit: 'month', step: 1, format: '%M' },
              {
                unit: 'quarter', step: 1, format: function (date) {
                  let dateToStr = ganttInstance.current.date.date_to_str('%M');
                  let endDate = ganttInstance.current.date.add(ganttInstance.current.date.add(date, 3, 'month'), -1, 'day');
                  return dateToStr(date) + ' - ' + dateToStr(endDate);
                }
              }
            ]
          },
          {
            name: 'year',
            scale_height: 50,
            min_column_width: 30,
            scales: [
              { unit: 'year', step: 1, format: '%Y' }
            ]
          }
        ]
      };

      ganttInstance.current.config.date_format = "%Y-%m-%d %H:%i:%s";
      ganttInstance.current.config.drag_move = false;
      ganttInstance.current.config.drag_multiple = false;
      ganttInstance.current.config.drag_progress = false;
      ganttInstance.current.config.drag_resize = false;
      ganttInstance.current.config.drag_project = false;
      ganttInstance.current.config.show_links = false;
      ganttInstance.current.config.columns = [
        { name: 'text', label: '资源', width: 160, tree: true, resize: true },
      ];

      ganttInstance.current.templates.tooltip_text = function (start, end, item) {
        if (item.capacity && item.mbom_num) {
          return `<b>${language.work_order_num}：</b>` + item.work_order_num  +
            `<br/><b>${language.batch_num}：</b>` + item.batch_order_num +
            `<br/><b>${language.product_name}：</b>` + item.product_name +
            `<br/><b>${language.mbom_num}：</b>` + item.mbom_num +
            `<br/><b>${language.process_num}：</b>` + item.process_num +
            (item.work_user_name ? (`<br/><b>派工人员：</b>` + item.work_user_name) : '') +
            (item.work_station_num ? (`<br/><b>派工工位：</b>` + item.work_station_num) : '') +
            (item.work_device_num ?(`<br/><b>派工设备：</b>` + item.work_device_num) : '') +
            `<br/><b>${language.begin_time}：</b>` + moment(item.start_date).format('YYYY-MM-DD HH:mm') +
            `<br/><b>${language.end_time}：</b>` + moment(item.end_date).format('YYYY-MM-DD HH:mm');
        } else if (item.capacity == 2) {
          return`<b>设备停机</b>` +
            `<br/><b>${language.begin_time}：</b>` + moment(item.start_date).format('YYYY-MM-DD HH:mm') +
            `<br/><b>${language.end_time}：</b>` + moment(item.end_date).format('YYYY-MM-DD HH:mm');
        } else if (item.capacity == 4) {
          return`<b>请假/休假</b>` +
            `<br/><b>${language.begin_time}：</b>` + moment(item.start_date).format('YYYY-MM-DD HH:mm') +
            `<br/><b>${language.end_time}：</b>` + moment(item.end_date).format('YYYY-MM-DD HH:mm');
        }
      }

      ganttInstance.current.templates.task_class = function(start, end, task){
        if(task.batch_order_num) {
          return "";
        }
        return "hide-task";
      };

      ganttInstance.current.plugins({
        fullscreen: true
      });

      ganttInstance.current.attachEvent("onTaskDblClick", function(){
        return false;
      });

      ganttInstance.current.attachEvent("onTaskClick", function(id){
        const task = ganttInstance.current.getTask(id);
        if (task && task.type === 'project') {
          // 展开/折叠子节点
          if (task.$open) {
            ganttInstance.current.close(id);
          } else {
            ganttInstance.current.open(id);
          }
          // 显示弹出框
          show(id);
          return false;
        }
        return false;
      });

      ganttInstance.current.attachEvent('onTaskOpened', function (id) {
        // 展开时不需要额外操作
      });

      ganttInstance.current.attachEvent('onTaskClosed', function (id) {
        // 可以在这里处理节点关闭时的逻辑
      });

      // 添加清除按钮事件
      ganttInstance.current.attachEvent("onBeforeTaskDrag", function(id, mode, e){
        if (e.ctrlKey) {
          // 如果按住 Ctrl 键点击，则清除该车间及其子节点的数据
          const task = ganttInstance.current.getTask(id);
          if (task && task.type === 'project') {
            const allTasks = ganttInstance.current.getDatastore('task').serialize();
            const tasksToRemove = allTasks.filter(t => 
              t.id === id || t.parent === id
            );
            tasksToRemove.forEach(t => {
              ganttInstance.current.deleteTask(t.id);
            });
            return false;
          }
        }
        return false;
      });

      ganttInstance.current.ext.zoom.init(zoomConfig);
      ganttInstance.current.ext.zoom.setLevel(model);
      ganttInstance.current.init(ganttRef.current);
      ganttInstance.current.parse({ data: [], links: [] });

    } catch (e) {
      console.error('Error in initGantt:', e);
    }
  }

  const toggleFullScreen = () => {
    if (ganttInstance.current?.ext?.fullscreen) {
      ganttInstance.current.ext.fullscreen.toggle();
    }
  }

  const show = (id) => {
    setValues({ id });
    setBatchList([]);
    setBomList([]);
    store.show();
  }

  const close = () => {
    store.close();
  }

  const searchBatchList = (payload: any) => {
    store.service.getAssignmentTask(payload).then(data => {
      setBatchList(data.map(item => ({
        ...item,
        label: item.batch_order_num,
        value: item.batch_order_num,
      })))
    })
  }

  const getTaskInfo = (isUpdate: boolean = false) => {
    if (!isUpdate) {
      setValues(prev => ({
        ...prev,
        work_device_id: null,
        work_user_id: null,
        work_station_id: null,
        time: null
      }));
    }
    store.service.getTaskInfo({id: values.id, batch_order_num: values.batch_order_num}).then(data => {
      setTask(data || {});
    })
  }

  const searchBomList = (payload:any) => {
    store.service.getTaskList(payload).then(data => {
      setBomList(data?.map((item: any) => ({
        ...item,
        label: `${item.mbom_num}`,
        value: item.id,
      })));
    })
  }

  const submit = () => {
    if (!values.id || !values.batch_order_num || !values.time) {
      message.error('请选择工序、批次、时间');
      console.log(values);
      
      return;
    }
    store.submit({
      id: values.id,
      batch_order_num: values.batch_order_num,
      time: values.time,
      work_user_id: values.work_user_id,
      work_station_id: values.work_station_id,
      work_device_id: values.work_device_id,
      capacity: task?.capacity,
      work_start: getDateTime(values.time[0]),
      work_end: getDateTime(values.time[1]),
      work_order_id: values.work_order_id?.value || values.work_order_id // 兼容老数据
    });
  }

  const onModelChange = (e: any) => {
    setModel(e.target.value);
    if (ganttInstance.current?.ext?.zoom) {
      try {
        ganttInstance.current.ext.zoom.setLevel(e.target.value);
      } catch (e) {
        console.error('Error changing zoom level:', e);
      }
    }
  }

  const { capacity, station_list = [], user_list = [], device_list = [], line_list = [] } = task || {};
  const stationOptions = (station_list ?? []).map(item => ({...item, label: item.station_num, value: item.id}));
  const userOptions = (user_list ?? []).map(item => ({...item, label: item.user_name, value: item.id}));
  const deviceOptions = (device_list ?? []).map(item => ({...item, label: item.device_num, value: item.id}));
  const lineOptions = (line_list ?? []).map(item => ({...item, label: item.line_num, value: item.id}));

  // 添加清除所有数据的方法
  const clearAllData = () => {
    if (ganttInstance.current) {
      ganttInstance.current.clearAll();
    }
  }

  // 添加 useEffect 监听 id 和 batch_order_num 变化，只有都不为 null 时才获取工序详情
  useEffect(() => {
    if (values.id && values.batch_order_num) {
      getTaskInfo();
    }
  }, [values.id, values.batch_order_num]);

  return <div className="page task-order-dispatch relative">
     <div className="toolbar flex-middle mb-10">
      <div className="flex-1">
        <Button type="primary" ghost onClick={clearAllData}>清除所有</Button>
        <Button style={{ marginLeft: 10 }} type="primary" ghost onClick={toggleFullScreen}>切换全屏</Button>
        <RadioGroup
          style={{ marginLeft: 15 }}
          value={model}
          onChange={onModelChange}
        >
          <Radio.Button value="hour">小时</Radio.Button>
          <Radio.Button value="day">天</Radio.Button>
          <Radio.Button value="week">周</Radio.Button>
          <Radio.Button value="month">月</Radio.Button>
          <Radio.Button value="quarter">季度</Radio.Button>
          <Radio.Button value="year">年</Radio.Button>
        </RadioGroup>
      </div>
      <RemoteSelect clearable
        onChange={store.onChange}
        service="depart"
        params={{ type: 2 }}
        style={{ width: 200 }}
        placeholder={language.pc_room}
      />
    </div>
    <div id="order-dispatch-gantt" className="flex-grow o-hidden"  ref={ganttRef}></div>
    <Spin style={{position: 'absolute', top: 0, left: 0, width: '100%', height: '100%'}} spinning={store.loading} tip="加载中..." />
    <div className="drawer">
      <Drawer
      width={1200}
     
        title={
          <div className="flex justify-between items-center">
            <span>派工</span>
            <CloseOutlined onClick={close} />
          </div>
        }
        size="large"
        closeOnOverlayClick={false}
        closeOnEscKeydown={false}
        destroyOnClose
        open={store.visible}
        onCancel={close}
        onClose={close}
         closable={false}
        
     
        footer={
          <div >
      <Button type="primary" onClick={submit} disabled={store.dialogLoading}>
            {language.confirm}
          </Button>
            <Button onClick={close} style={{ marginLeft: 8 }}>取消</Button>
    
          </div>
        }
      >
        <Spin spinning={store.dialogLoading} tip={language.loading}>
          <Form
            key={`${values.id}_${values.batch_order_num}`}
            labelAlign="left"
            labelCol={{ span: 24 }}
            initialValues={values}
            onValuesChange={(changedValues) => {
              setValues(prev => ({ ...prev, ...changedValues }));
            }}
          >
            <Form.Item label="工单" name="work_order_id" rules={[{required: true, message: '请选择工单'}]}>
              <AsyncSelect service="workOrder" onChange={(value, option) => {
                setBatchList([]);
                setBomList([]);
                // 兼容option为对象或label在context
                const label = option?.label || (option && option.children) || value;
                setValues({work_order_id: { label, value }, batch_order_num: null, id: null});
                searchBatchList({work_order_id: value});
              }} />
            </Form.Item>
            <Form.Item label={language.batch_num} name="batch_order_num" rules={[{required: true, message: '请选择批次'}]}>
              <Select 
                options={batchList} 
                onChange={(value) => {
                  setValues(prev => ({...prev, batch_order_num: value, id: null}));
                  searchBomList({batch_order_num: value});
                }} 
              />
            </Form.Item>
            <Form.Item label={<span className="required">工序</span>} name="id" rules={[{required: false, message: '请选择工序'}]}>
              <div className="w100">
                <div className={Style.bomList}>
                  {
                    bomList.map((bom: any, index: number) => (
                      <React.Fragment key={`${bom.value}_${index}`}>
                        <div
                          className={classNames(Style.bomItem, values.id === bom.value ? Style.activeBom : '', `pointer relative flex-center`)}
                          style={{backgroundColor: bom.bom_color}}
                          onClick={() => {
                            setValues(prev => ({
                              ...prev,
                              id: bom.value,
                              work_device_id: null,
                              work_user_id: null,
                              work_station_id: null,
                              time: null
                            }));
                          }}
                        >
                          <div style={{display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: '100%'}}>
                            <span style={{fontSize: "16px", color: hexToBackRGB(bom.bom_color)}}>{ bom.mbom_num }</span>
                            <span style={{fontSize: "14px", color: '#222', marginTop: 2}}>{ bom.process_name }</span>
                          </div>
                          {
                            values.id === bom.value && <Checkbox className={Style.activeBomCheck} checked />
                          }
                        </div>
                        {
                          index < (bomList.length - 1) && <img src={ArrowSvg} alt="arrow" className={Style.jianTou} />
                        }
                      </React.Fragment>
                    ))
                  }
                </div>
                {
                  !values?.id && <div className="error">请选择开始工序</div>
                }
              </div>
            </Form.Item>
            {
              capacity === 2 && (
                <Form.Item 
                  label={language.equipment} 
                  name="work_device_id" 
                  rules={[{required: true, message: language.base.pc_equipment}]}
                >
                  <Select options={deviceOptions} />
                </Form.Item>
              )
            }
            {
              capacity === 4 && (
                <Form.Item 
                  label="人员" 
                  name="work_user_id" 
                  rules={[{required: true, message: language.base.pc_person}]}
                >
                  <Select options={userOptions} />
                </Form.Item>
              )
            }
            {
              [1,3].includes(capacity) && (
                <Form.Item 
                  label={language.station} 
                  name="work_station_id" 
                  rules={[{required: true, message: language.base.pc_station}]}
                >
                  <Select options={stationOptions} />
                </Form.Item>
              )
            }
            {
              capacity === 5 && (
                <Form.Item
                  label="产线"
                  name="work_line_id"
                  rules={[{ required: true, message: '请选择产线' }]}
                >
                  <Select options={lineOptions} />
                </Form.Item>
              )
            }
            <Form.Item 
              label="时间" 
              name="time" 
              rules={[{required: true, message: '请选择时间'}]}
            >
              <DateRangePicker showTime />
            </Form.Item>
          </Form>
        </Spin>
      </Drawer>
    </div>
  </div>
})

export default OrderDispatch;
